package com.thinkit.bigdata.web.filter;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by BanAiQin on 2017/4/20.
 * 自定义session超时过滤器，判断是否为ajax请求
 * 当session失效时，判断是否为ajax请求，若是ajax请求，则返回错误码588
 * 否之，直接返回到登陆页面
 */
public class MyAuthenticationFilter extends FormAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(MyAuthenticationFilter.class);

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return this.executeLogin(request, response);
            } else {
                // 判断是否是ajax请求
                if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
                    HttpServletResponse res = WebUtils.toHttp(response);
                    res.sendError(588);
                }
                return true;
            }
        } else {
            // 判断是否是ajax请求
            if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
                HttpServletResponse res = WebUtils.toHttp(response);
                res.sendError(588);
            } else {
                redirectToLogin(request, response);
            }
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
    }


}
